<script setup>
import { ref, computed } from 'vue'
import { onReachBottom, onLoad } from "@dcloudio/uni-app"
import OrderList from './components/OrderList.vue'
import { getMyInOutListApi } from '@/apis/orderManagement.js'
import { inOutStatus, outStatus } from '@/apis/dict.js'
import { carListApi } from '@/apis/car.js'
import store from '@/store/index.js'

// 是否外部客户
const isExternal = computed(() => store.state.isExternal)

const params = ref({
  pageNum: 1,
  pageSize: 10,
})
const orderList = ref([])
const loadStatus = ref({
  status: "loadmore",
  noMore: false,
  loading: false
})
const type = ref('inorder') // inorder, outorder
onLoad(async (options) => {
  type.value = options.type
  uni.setNavigationBarTitle({ title: options.type === 'inorder' ? '订单入库' : '订单出库' })
  await getStatus()
  await getCarList()
  await getData()
})

const statusList = ref([])
const getStatus = async () => {
  let res = null
  if (type.value === 'inorder') {
    res = await inOutStatus()
  } else {
    res = await outStatus()
  }
  statusList.value = res.data
}
const carList = ref([])
const getCarList = async () => {
  const res = await carListApi({ pageSize: 100, pageNum: 1 })
  carList.value = res.rows
}

const getData = async () => {
  try {
    const res = await getMyInOutListApi(params.value, type.value)
    const { rows, total } = res
    if (total === 0) return
    const arr = rows.map(item => {
      const status = statusList.value.find(i => i.dictValue === item.status)
      const car = carList.value.find(i => i.id === item.carid)
      return {
        ...item,
        statusStr: status?.dictLabel || '未知状态',
        carStr: car?.platenumber || '未知车辆',
        currentId: item.id.substring(0, 8) + '...' + item.id.substring(item.id.length - 4, item.id.length),
      }
    })
    if (params.value.pageNum === 1) {
      orderList.value = arr
    } else {
      orderList.value = [...orderList.value, ...arr]
    }
    if (arr.length < params.value.pageSize || orderList.value.length >= total) {
      loadStatus.value.noMore = true
      loadStatus.value.status = "nomore"
    } else {
      loadStatus.value.status = "loadmore"
    }
    params.value.pageNum++
  } catch (error) {
    loadStatus.value.status = "loadmore"
  } finally {
    loadStatus.value.loading = false
  }
}

onReachBottom(() => {
  if (!loadStatus.value.noMore) {
    getData()
  }
})

const handlerGoods = (item) => {
  const data = JSON.stringify(item)
  uni.navigateTo({
    url: `/pages/orderManagement/goods?data=${data}&type=${type.value}`
  })
}

// 出来搜索
const formData = ref({
  company: '',
  beginCreatedate: '',
  endCreatedate: '',
  beginExpectdate: "",
  endExpectdate: "",
  status: ""
})
const statusText = ref('')
const isFormVisible = ref(false)
const bingDateShow = ref(false)
const expectDateShow = ref(false)
const showStatus = ref(false)
const toggleFormVisibility = () => {
  isFormVisible.value = !isFormVisible.value
}
const handlerSearch = () => {
  const { company, beginCreatedate, endCreatedate, beginExpectdate, endExpectdate, status } = formData.value
  init()
  params.value = {
    pageNum: 1,
    pageSize: 10,
    company,
    status,
    ['params[beginCreatedate]']: beginCreatedate,
    ['params[endCreatedate]']: endCreatedate,
    ['params[beginExpectdate]']: beginExpectdate,
    ['params[endExpectdate]']: endExpectdate
  }
  getData()
}
const handlerReset = () => {
  formData.value = {
    company: '',
    beginCreatedate: '',
    endCreatedate: '',
    beginExpectdate: "",
    endExpectdate: "",
    status: ""
  }
  init()
  getData()
}
const changeCreationDate = e => {
  formData.value.beginCreatedate = e.startDate
  formData.value.endCreatedate = e.endDate
}
const changeEstimatedDate = e => {
  formData.value.beginExpectdate = e.startDate
  formData.value.endExpectdate = e.endDate
}
const statusChange = e => {
  formData.value.status = statusList.value[e[0]].dictValue
  statusText.value = statusList.value[e[0]].dictLabel
}
const init = () => {
  params.value = {
    pageNum: 1,
    pageSize: 10,
  }
  loadStatus.value.noMore = false
  loadStatus.value.status = "loadmore"
  orderList.value = []
}
</script>

<template>
  <view class="page_container">
    <u-sticky>
      <view class="search_container flex_sb" @click="toggleFormVisibility">
        <text>搜索内容</text>
        <view>
          {{ isFormVisible ? '收起' : '展开' }}
          <u-icon :name="isFormVisible ? 'arrow-up' : 'arrow-down'" size="20"></u-icon>
        </view>
      </view>
      <view class="sticky-form-container" v-show="isFormVisible">
        <u-form :model="formData" label-width="200" class="form-container">
          <u-form-item label="客户名称:" v-if="!isExternal">
            <u-input v-model="formData.company" placeholder="请输入计划名称" class="search-input" />
          </u-form-item>
          <u-form-item label="建单日期:">
            <view v-if="!formData.beginCreatedate" class="date-picker" @click="bingDateShow = true">请选择建单日期</view>
            <view v-else @click="bingDateShow = true">{{ formData.beginCreatedate }} - {{ formData.endCreatedate }}</view>
          </u-form-item>
          <u-form-item :label="type === 'inorder' ? '预计到达时间:' : '预计出库时间:'">
            <view v-if="!formData.beginExpectdate" class="date-picker" @click="expectDateShow = true">请选择预计到达时间</view>
            <view v-else @click="expectDateShow = true">{{ formData.beginExpectdate }} - {{ formData.endExpectdate }}
            </view>
          </u-form-item>
          <u-form-item label="状态:">
            <u-input v-model="statusText" @click="showStatus = true" placeholder="请选择状态" class="search-input" />
          </u-form-item>
          <u-form-item>
            <view style="display: flex;justify-content: space-around;">
              <u-button type="primary" size="medium" @click="handlerSearch">搜索</u-button>
              <u-button type="default" size="medium" @click="handlerReset">重置</u-button>
            </view>
          </u-form-item>
        </u-form>
      </view>
    </u-sticky>
    <OrderList :orderList="orderList" :loadStatus="loadStatus.status" :type="type" @clickGoods="handlerGoods" />
  </view>
  <u-calendar v-model="bingDateShow" mode="range" @change="changeCreationDate"></u-calendar>
  <u-calendar v-model="expectDateShow" mode="range" @change="changeEstimatedDate"></u-calendar>
  <u-picker v-model="showStatus" mode="selector" :range="statusList" range-key="dictLabel"
    @confirm="statusChange"></u-picker>
</template>

<style lang="scss" scoped>
.form-container {
  background: #fff;
  z-index: 99;
}

.search_container {
  height: 100rpx;
  padding: 0 20rpx;
  background: #fff;
  z-index: 99;
  font-size: $list-font-size;


}
</style>
